import { dataCollectionApi } from '@/assets/api/dataCollection.js'

export default {
  name: 'DataCollection',
  data() {
    return {
      activeTab: 'manual',
      tabs: [
        { key: 'manual', label: '手工录入', icon: '✍️' },
        { key: 'csv', label: 'CSV上传', icon: '📁' },
        { key: 'pending', label: '待入库数据', icon: '📋' }
      ],
      
      // 手工录入表单
      manualForm: {
        customsArea: '',
        declareNo: '',
        itemNo: '',
        currencyType: '',
        amountCny: null,
        amountUsd: null,
        goodsQuantity: null,
        userId: 1 // 临时设置，实际应从用户登录信息获取
      },
      
      // CSV上传表单
      csvForm: {
        customsArea: '',
        userId: ''
      },
      
      // 待入库数据筛选
      pendingFilter: {
        customsArea: ''
      },
      
      // 基础数据
      customsAreas: [],
      users: [],
      pendingList: [],
      selectedItems: [],
      selectedFile: null,
      
      // 状态控制
      submitting: false,
      uploading: false,
      batchProcessing: false,
      warehousingIds: [],
      
      // 分页
      currentPage: 1,
      pageSize: 10,
      
      // 消息提示
      message: {
        show: false,
        type: 'success',
        text: ''
      }
    }
  },
  
  mounted() {
    this.loadBasicData()
    this.loadPendingList()
  },
  
  methods: {
    // 切换选项卡
    switchTab(tab) {
      this.activeTab = tab
      if (tab === 'pending') {
        this.loadPendingList()
      }
    },
    
    // 加载基础数据
    async loadBasicData() {
      try {
        const [areasRes, usersRes] = await Promise.all([
          dataCollectionApi.getCustomsAreaList(),
          dataCollectionApi.getUserList()
        ])
        
        if (areasRes.code === 200) {
          this.customsAreas = areasRes.data
        }
        if (usersRes.code === 200) {
          this.users = usersRes.data
        }
      } catch (error) {
        this.showMessage('error', '加载基础数据失败')
      }
    },
    
    // 提交手工录入数据
    async submitManualData() {
      this.submitting = true
      try {
        const response = await dataCollectionApi.manualInput(this.manualForm)
        if (response.code === 200) {
          this.showMessage('success', '数据录入成功')
          this.resetManualForm()
          if (this.activeTab === 'pending') {
            this.loadPendingList()
          }
        } else {
          this.showMessage('error', response.message || '数据录入失败')
        }
      } catch (error) {
        this.showMessage('error', '系统异常，请稍后重试')
      } finally {
        this.submitting = false
      }
    },
    
    // 重置手工录入表单
    resetManualForm() {
      this.manualForm = {
        customsArea: '',
        declareNo: '',
        itemNo: '',
        currencyType: '',
        amountCny: null,
        amountUsd: null,
        goodsQuantity: null,
        userId: 1
      }
    },
    
    // 处理文件选择
    handleFileSelect(event) {
      const file = event.target.files[0]
      if (file) {
        this.validateAndSetFile(file)
      }
    },
    
    // 处理拖拽上传
    handleDrop(event) {
      event.preventDefault()
      const files = event.dataTransfer.files
      if (files.length > 0) {
        this.validateAndSetFile(files[0])
      }
    },
    
    // 验证并设置文件
    validateAndSetFile(file) {
      if (!file.name.toLowerCase().endsWith('.csv')) {
        this.showMessage('error', '请选择CSV格式文件')
        return
      }
      if (file.size > 10 * 1024 * 1024) {
        this.showMessage('error', '文件大小不能超过10MB')
        return
      }
      this.selectedFile = file
    },
    
    // 移除文件
    removeFile() {
      this.selectedFile = null
      this.$refs.fileInput.value = ''
    },
    
    // 上传CSV文件
    async uploadCSV() {
      if (!this.selectedFile || !this.csvForm.customsArea || !this.csvForm.userId) {
        this.showMessage('error', '请完善上传信息')
        return
      }
      
      this.uploading = true
      try {
        const formData = new FormData()
        formData.append('file', this.selectedFile)
        formData.append('customsArea', this.csvForm.customsArea)
        formData.append('userId', this.csvForm.userId)
        
        const response = await dataCollectionApi.csvUpload(formData)
        if (response.code === 200) {
          this.showMessage('success', response.data)
          this.removeFile()
          this.csvForm = { customsArea: '', userId: '' }
          if (this.activeTab === 'pending') {
            this.loadPendingList()
          }
        } else {
          this.showMessage('error', response.message || 'CSV上传失败')
        }
      } catch (error) {
        this.showMessage('error', '系统异常，请稍后重试')
      } finally {
        this.uploading = false
      }
    },
    
    // 加载待入库数据列表
    async loadPendingList() {
      try {
        const params = {
          page: this.currentPage,
          size: this.pageSize,
          ...this.pendingFilter
        }
        
        const response = await dataCollectionApi.getPendingList(params)
        if (response.code === 200) {
          this.pendingList = response.data
        }
      } catch (error) {
        this.showMessage('error', '加载数据失败')
      }
    },
    
    // 刷新待入库列表
    refreshPendingList() {
      this.currentPage = 1
      this.selectedItems = []
      this.loadPendingList()
    },
    
    // 单个数据入库
    async warehousingData(collectionId) {
      this.warehousingIds.push(collectionId)
      try {
        const response = await dataCollectionApi.warehousing({
          collectionId: collectionId,
          userId: 1 // 临时设置
        })
        
        if (response.code === 200) {
          this.showMessage('success', '数据入库成功')
          this.loadPendingList()
        } else {
          this.showMessage('error', response.message || '数据入库失败')
        }
      } catch (error) {
        this.showMessage('error', '系统异常，请稍后重试')
      } finally {
        this.warehousingIds = this.warehousingIds.filter(id => id !== collectionId)
      }
    },
    
    // 批量入库
    async batchWarehousing() {
      if (this.selectedItems.length === 0) {
        this.showMessage('warning', '请选择要入库的数据')
        return
      }
      
      this.batchProcessing = true
      try {
        let successCount = 0
        for (const collectionId of this.selectedItems) {
          try {
            const response = await dataCollectionApi.warehousing({
              collectionId: collectionId,
              userId: 1
            })
            if (response.code === 200) {
              successCount++
            }
          } catch (error) {
            console.error(`入库失败: ${collectionId}`, error)
          }
        }
        
        this.showMessage('success', `批量入库完成，成功处理${successCount}条数据`)
        this.selectedItems = []
        this.loadPendingList()
      } catch (error) {
        this.showMessage('error', '批量入库异常')
      } finally {
        this.batchProcessing = false
      }
    },
    
    // 分页切换
    changePage(page) {
      if (page >= 1) {
        this.currentPage = page
        this.loadPendingList()
      }
    },
    
    // 工具方法
    getDataTypeText(type) {
      const types = {
        1: 'FTP导入',
        2: 'CSV上报',
        3: '手工录入',
        4: '主动采集'
      }
      return types[type] || '未知'
    },
    
    getDataTypeClass(type) {
      const classes = {
        1: 'ftp',
        2: 'csv',
        3: 'manual',
        4: 'active'
      }
      return classes[type] || ''
    },
    
    getCurrencyText(type) {
      return type === 1 ? '人民币' : type === 2 ? '美元' : '未知'
    },
    
    formatAmount(amount) {
      return amount ? amount.toLocaleString() : '0.00'
    },
    
    formatDateTime(dateTime) {
      if (!dateTime) return ''
      return new Date(dateTime).toLocaleString('zh-CN')
    },
    
    formatFileSize(size) {
      if (size < 1024) return size + 'B'
      if (size < 1024 * 1024) return (size / 1024).toFixed(1) + 'KB'
      return (size / (1024 * 1024)).toFixed(1) + 'MB'
    },
    
    getMessageIcon(type) {
      const icons = {
        success: '✅',
        error: '❌',
        warning: '⚠️',
        info: 'ℹ️'
      }
      return icons[type] || 'ℹ️'
    },
    
    showMessage(type, text) {
      this.message = { show: true, type, text }
      setTimeout(() => {
        this.message.show = false
      }, 3000)
    }
  }
}
